package com.example.privacy;

import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import com.example.privacy.Utils.SharedPreferencesUtils;
import com.squareup.picasso.Picasso;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import java.util.ArrayList;

public class CustomerMenu extends AppCompatActivity {
    private static final int PERMISSION_CAMERA_REQUEST_CODE = 0x00000012;
    public Button goQrScann;
    private TextView textView;
    private Button logout;
    private ArrayList<Good> goods;
    private RecyclerView recyclerView;
    private CustomAdapter adapter;
    private RecyclerView.LayoutManager mLayoutManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer_menu);
        logout = (Button)findViewById(R.id.CustomerLogOut);
        textView = (TextView) findViewById(R.id.textView3);
        textView.setText(SharedPreferencesUtils.getInstance(CustomerMenu.this).getString("username")+"客户端");
        recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
        mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferencesUtils.getInstance(CustomerMenu.this).putString("username","");
                SharedPreferencesUtils.getInstance(CustomerMenu.this).putString("password","");
                SharedPreferencesUtils.getInstance(CustomerMenu.this).putString("token","");
                SharedPreferencesUtils.getInstance(CustomerMenu.this).putString("type","");
                Intent i = new Intent(CustomerMenu.this,LoginActivity.class);
                startActivity(i);
                CustomerMenu.this.finish();
            }
        });
        goQrScann = (Button)findViewById(R.id.button5);
        goQrScann.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(CustomerMenu.this, QRScannActivity.class);
                startActivity(i);
            }
        });
        GetAllGoods();
        checkPermissionAndCamera();
    }
    private void checkPermissionAndCamera() {
        int hasCameraPermission = ContextCompat.checkSelfPermission(getApplication(),
                Manifest.permission.CAMERA);
        if (hasCameraPermission == PackageManager.PERMISSION_GRANTED) {

        } else {
            //没有权限，申请权限。
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
                    PERMISSION_CAMERA_REQUEST_CODE);
        }
    }
    /**
     * 处理权限申请的回调。
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        if (requestCode == PERMISSION_CAMERA_REQUEST_CODE) {
            System.out.print("到这里执行");
            System.out.print(PackageManager.PERMISSION_GRANTED);
            System.out.print(grantResults[0]);
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //允许权限，有调起相机拍照。
            } else {
                //拒绝权限，弹出提示框。
                Toast.makeText(this, "拍照权限被拒绝", Toast.LENGTH_LONG).show();
            }
        }
    }

    public static class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder>    {

        private Good[] localDataSet;
        public static class ViewHolder extends RecyclerView.ViewHolder {
            private final TextView goodTitle;
            private final TextView goodState;
            private final ImageView imageView;

            public ViewHolder(View view) {
                super(view);
                goodTitle = (TextView) view.findViewById(R.id.goods_title);
                goodState = (TextView) view.findViewById(R.id.goods_state);
                imageView = (ImageView) view.findViewById(R.id.goods_picture);
            }
            public void setTextView(String title, String state) {
                goodTitle.setText(title);
                goodState.setText(state);
                Picasso.get().load("https://picsum.photos/200").into(imageView);
            }
        }

        public CustomAdapter(Good[] dataSet) {
            localDataSet = dataSet;
        }
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext())
                    .inflate(R.layout.layout, viewGroup, false);
            return new ViewHolder(view);
        }
        @Override
        public void onBindViewHolder(ViewHolder viewHolder, final int position) {
            viewHolder.setTextView(localDataSet[position].getGoodsName(),localDataSet[position].getNowLocal());
        }

        @Override
        public int getItemCount() {
            return localDataSet.length;
        }
    }

    public void GetAllGoods(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                String url = getString(R.string.baseUrl)+"/GetAllGoods";
                System.out.println(url);
                final OkHttpClient client = new OkHttpClient();
                RequestBody body = RequestBody.create(null,"");
                final Request request = new Request.Builder()
                        .url(url)
                        .addHeader("Authorization","Bearer "+ SharedPreferencesUtils.getInstance(CustomerMenu.this).getString("token"))
                        .post(body)
                        .build();
                try {
                    Response response = client.newCall(request).execute();
                    if(response.code()==200){
                        final String result = response.body().string();
                        goods = JSONArray.parseObject(result, new TypeReference<ArrayList<Good>>() {
                        });
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                adapter = new CustomAdapter(goods.toArray(new Good[goods.size()]));
                                recyclerView.setLayoutManager(mLayoutManager);
                                recyclerView.setAdapter(adapter);
                            }
                        });
                        System.out.println(result);
                    }else{

                    }
                    response.body().close();
                }catch (Exception e){
                    System.out.println(e.getMessage().toString());
                }
            }
        }).start();
    }
}